package utils;

import play.Logger;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

/**
 * @author zhangzc@djcars.cn
 * @create 2016/11/29
 */
public class WXBizDataCryptUtil {

    public static boolean initialized = false;

    public static void main(String[] args) throws Exception  {
        /*String sessionKey  = "7TukevELoDLbxRZMb/XjoA==";
        String encryptedData  = "fVXNpH9P+l/CkJYbkTLtThTOGwyxblIbzCo5+3B1KY6RIi6sI1RgQEI3Y6h3YM5V9VYfeUBlr9hrPVjC6/1FLY9u4SPDP0wASaWl/7z3rXD8z1n8fZD9ym2DFlUU9uSfj2HqFUTRtLZJczd9qYFv3A6OJpCI35aB7JXsOdrOJOqQJBN72kJQXMFspmckxPwRY1T4PBCLr2GErG0wMfdNALAjLTJamPeTu8rh6r+QoxrdGgi54rvFP7+y99JNpqmR68908Mbe27gjc+sLPofXbc/a0FPcuPqJkGU6aMYGtrAfMvwKFB0nlmwTD4eDTLBPLwBvqDhN2kMdw3pTIEqq+IHIESxGF+sq7X1cfFCGBZ08hdgWZuxH5wkfSjejMXVZ3XdOI50azVb82UAtcH69PgO55XtW0xRiQvWNHkR4VYdv7YVkATYLeMrXde6ZYVMfE4m+cUToSEs8jouisXwFOagBEDXHVQAICFw7itarlPhkSiZXCKPhSkGdMoXhcd3a/PTeMX4n9U0w3UGGyj9/aQ=";
        String iv = "0qeI4Lw5WjR5RaldSglxDw==";
        String userInfo= decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));

        Logger.info(userInfo);*/
    }

    /**
     * 对称解密使用的算法为 AES-128-CBC，数据采用PKCS#7填充。
     * 对称解密的目标密文为 Base64_Decode(encryptedData),
     * 对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节
     * 对称解密算法初始向量 iv 会在数据接口中返回。
     * @param content
     * @param keyByte
     * @param ivByte
     * @return
     */
    public static String decrypt(byte[] content, byte[] keyByte, byte[] ivByte) {
        initialize();
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");

            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);
            return new String(result);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return  "";
    }

    public static void initialize(){
        if (initialized) return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }
    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }
}
